package com.settlement.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.settlement.system.common.constant.SystemConstants;
import com.settlement.system.mapper.SysAuditRuleMapper;
import com.settlement.system.model.bo.AuditRuleFormBO;
import com.settlement.system.model.entity.SysAuditRule;
import com.settlement.system.model.form.AuditRuleForm;
import com.settlement.system.model.query.AuditRulePageQuery;
import com.settlement.system.service.SysAuditRuleService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 * 稽核规则 服务实现类
 * </p>
 *
 * @author huangrensen
 * @since 2023-08-14
 */
@Service
@RequiredArgsConstructor
public class SysAuditRuleServiceImpl extends ServiceImpl<SysAuditRuleMapper, SysAuditRule> implements SysAuditRuleService {

    private final RedisTemplate redisTemplate;

    @Override
    public Page<SysAuditRule> getAuditRulePage(AuditRulePageQuery queryParams) {
        // 查询参数
        int pageNum = queryParams.getPageNum();
        int pageSize = queryParams.getPageSize();
        String keywords = queryParams.getKeywords();
        // 查询数据
        return this.page(new Page<>(pageNum, pageSize), new LambdaQueryWrapper<SysAuditRule>().like(StrUtil.isNotBlank(keywords), SysAuditRule::getRuleName, keywords)
                .or().like(StrUtil.isNotBlank(keywords), SysAuditRule::getRuleCode, keywords).orderByAsc(true, SysAuditRule::getPriority, SysAuditRule::getRuleCode));
    }

    @Override
    @SuppressWarnings("unchecked")
    public boolean saveRule(AuditRuleForm ruleForm) {
        String ruleCode = ruleForm.getRuleCode();
        long count = this.count(new LambdaQueryWrapper<SysAuditRule>().eq(SysAuditRule::getRuleCode, ruleCode));
        Assert.isTrue(count == 0, "规则编号已存在");
        String ruleName = ruleForm.getRuleName();
        count = this.count(new LambdaQueryWrapper<SysAuditRule>().eq(SysAuditRule::getRuleName, ruleName));
        Assert.isTrue(count == 0, "规则名称已存在");
        SysAuditRule sysAuditRule = new SysAuditRule();
        BeanUtil.copyProperties(ruleForm, sysAuditRule);
        boolean result = this.save(sysAuditRule);
        // 删除缓存
        redisTemplate.delete(SystemConstants.RULER_CACHE_ALL);
        return result;
    }

    @Override
    @SuppressWarnings("unchecked")
    public void updateRule(Long ruleId, AuditRuleForm ruleForm) {
        String ruleCode = ruleForm.getRuleCode();
        long count = this.count(new LambdaQueryWrapper<SysAuditRule>().eq(SysAuditRule::getRuleCode, ruleCode).ne(SysAuditRule::getId, ruleId));
        Assert.isTrue(count == 0, "规则编号已存在");
        String ruleName = ruleForm.getRuleName();
        count = this.count(new LambdaQueryWrapper<SysAuditRule>().eq(SysAuditRule::getRuleName, ruleName).ne(SysAuditRule::getId, ruleId));
        Assert.isTrue(count == 0, "规则名称已存在");
        SysAuditRule sysAuditRule = this.getById(ruleId);
        BeanUtil.copyProperties(ruleForm, sysAuditRule, "id");
        this.baseMapper.update(sysAuditRule);
        // 删除缓存
        redisTemplate.delete(SystemConstants.RULER_CACHE_ALL);
    }

    @Override
    @SuppressWarnings("unchecked")
    public boolean deleteRules(String idsStr) {
        Assert.isTrue(StrUtil.isNotBlank(idsStr), "删除的规则数据为空");
        // 逻辑删除
        List<Long> ids = Arrays.stream(idsStr.split(",")).map(Long::parseLong).collect(Collectors.toList());
        boolean result = this.removeByIds(ids);
        // 删除缓存
        redisTemplate.delete(SystemConstants.RULER_CACHE_ALL);
        return result;
    }

    @Override
    public AuditRuleForm getRoleFormData(Long ruleId) {
        AuditRuleFormBO auditRuleFormBO = this.baseMapper.getRuleDetail(ruleId);
        AuditRuleForm auditRuleForm = new AuditRuleForm();
        BeanUtil.copyProperties(auditRuleFormBO, auditRuleForm);
        return auditRuleForm;
    }

    @Override
    @SuppressWarnings("unchecked")
    public List<SysAuditRule> getAll() {
        Object value = redisTemplate.opsForValue().get(SystemConstants.RULER_CACHE_ALL);
        if (value != null) {
            List<SysAuditRule> rules = (List<SysAuditRule>) value;
            if (rules.size() > 0) {
                rules.sort(Comparator.comparing(SysAuditRule::getPriority));
                return rules;
            }
        }
        List<SysAuditRule> rules = this.list();
        // 加入缓存
        rules.sort(Comparator.comparing(SysAuditRule::getPriority));
        redisTemplate.opsForValue().set(SystemConstants.RULER_CACHE_ALL, rules, 1, TimeUnit.HOURS);
        return rules;
    }
}
